<script setup lang="ts">
import { frequencyType, freeType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";
import QuestionSelector from "./QuestionSelector.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  currencyList: Array<any> = inject("currencyList", []),
  activityBaseInfo: any = inject("activityBaseInfo", {}),
  activityReadonly = inject("activityReadonly");

const form = ref<any>({
    partType: 0,
    freeType: 4,
    partTotalLimit: 0,
    lotteryTotalLimit: 0,
    lotteryLimitType: 0,
  }),
  prizeAreas = ref<Array<any>>([]),
  answerConfig = ref<any>({
    lotteryConfig: 1,
    orderType: 0,
    scoreType: 0,
    typeScoreList: [{ perScore: "" }],
    completeQua: 0,
    rewardLimit: 0,
    rewardConfigList: [{ rewardList: [{}] }],
    questionList: [],
  });

const formRef = ref(),
  poolRef = ref(),
  answerRef = ref();

const validateTimer = (rule: any, value: any, callback: any) => {
  if (rule.field === "completeScore" && answerConfig.value.completeQua == 2) {
    if (value === "" || value === undefined)
      callback(new Error(`请输入限制时间`));
  } else if (
    (rule.field === "ansTotalTime" || rule.field === "ansPerTime") &&
    (answerConfig.value.ansTimeLimit == 1 ||
      answerConfig.value.ansTimeLimit == 2)
  ) {
    if (value === "" || value === undefined)
      callback(new Error(`请输入限制时间`));
    callback();
  }
  callback();
};

const validateQuestionNum = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error(`请输入题目数量`));
  }
  if (value == 0) {
    callback(new Error(`题目数量不能为0`));
  }
  if (value > answerConfig.value.questionList.length) {
    callback(new Error(`答题数量不能超过题目总数量`));
  }
  callback();
};

const rules = {
  lotteryTotalNum: [
    { required: true, message: "请输入中奖总次数", trigger: "blur" },
  ],
  questionNum: [{ validator: validateQuestionNum, trigger: "blur" }],
  orderType: [{ required: true, message: "请选择出题顺序", trigger: "change" }],
  ansTimeLimit: [
    { required: true, message: "请选择答题时间类型", trigger: "change" },
  ],
  ansTotalTime: [{ validator: validateTimer, trigger: "blur" }],
  ansPerTime: [{ validator: validateTimer, trigger: "blur" }],
  scoreType: [
    { required: true, message: "请选择答题分数类型", trigger: "change" },
  ],
  completeQua: [
    { required: true, message: "请选择通关条件", trigger: "change" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit:
      val.pageArea.partLimit && typeof val.pageArea.partLimit === "string"
        ? JSON.parse(val.pageArea.partLimit)
        : [{ type: 1, limitNum: 1 }],
  });
  answerConfig.value = val.actQuestionConfig
    ? Object.assign({}, val.actQuestionConfig, { lotteryConfig: 1 })
    : Object.assign({}, answerConfig.value, {
        pageFlag: form.value.pageFlag,
      });
  prizeAreas.value = val.prizeAreas || [];
  updateData();
};

const limitsDisabled = computed(() => {
  return form.value.hasTicket == 1 && activityBaseInfo.value.status == 2;
});

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (answerConfig.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

const quotePrize = computed(() => {
  let prize: Array<any> = [];
  let rewardConfigList = answerConfig.value.rewardConfigList || [];
  for (let i = 0; i < rewardConfigList.length; i++) {
    let list = rewardConfigList[i].rewardList.filter((item: any) => {
      if (item.rewardType === "PRIZE") {
        return true;
      }
      return false;
    });
    prize = prize.concat(list || []);
  }
  if (prize && prize.length > 0) {
    return prize.map((item: any) => {
      return {
        prizeId: item.prizeId,
        poolId: item.prizeArea,
        specId: item.prizeSpec,
      };
    });
  }
  return [];
});

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

// 添加奖池奖品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

// 添加奖励
const addReward = () => {
  answerConfig.value.rewardConfigList.push({ rewardList: [{}] });
};

// 切换分数类型
const changeScoreType = (type: number) => {
  if (type == 0) {
    answerConfig.value.typeScoreList = [{ perScore: "" }];
  } else if (type == 1) {
    answerConfig.value.typeScoreList = [{ checkScore: "", selectScore: "" }];
  } else if (type == 2) {
    let typeScoreList = [];
    for (let i = 0; i < 5; i++) {
      typeScoreList.push({ star: i + 1, starScore: "" });
    }
    answerConfig.value.typeScoreList = typeScoreList;
  }
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actQuestionConfig: answerConfig.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let actQuestionConfig = {};
        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        // 每人参与限制
        if (detail.partLimit)
          detail.partLimit = JSON.stringify(detail.partLimit);

        try {
          actQuestionConfig = await checkShare();
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actQuestionConfig: actQuestionConfig,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

// 答题参数校验
const checkShare = (): any => {
  return new Promise((resolve, reject) => {
    answerRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(answerConfig.value);
        detail.rewardConfigList.forEach((reward: any) => {
          reward.rewardList.forEach((item: any) => {
            if (item.lotteryAreaUid) item.lotteryArea = "";
            if (item.prizeAreaUid) item.prizeArea = "";
            if (item.prizeUid) item.prizeId = "";
            if (item.prizeSpecUid) item.prizeSpec = "";
            if (item.ticketAct === "local") item.ticketAct = "";
          });
        });
        resolve(detail);
      } else reject(`请检查${form.value.name}`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    :disabled="activityReadonly || limitsDisabled"
    label-width="auto"
  >
    <h3 class="collpase-title">参与限制</h3>
    <el-form-item label="参与消耗：">
      <el-radio-group v-model="form.partType">
        <el-radio :label="0">不消耗</el-radio>
        <el-radio :label="1">积分</el-radio>
        <el-radio :label="2">现金</el-radio>
        <!-- <el-radio :label="3">现金+积分</el-radio> -->
      </el-radio-group>
    </el-form-item>
    <!-- 现金 -->
    <template v-if="form.partType == 2 || form.partType == 3">
      <el-form-item prop="price">
        <EasyNumberInput
          v-model="form.price"
          :min="0.01"
          :max="9999"
          unit="元"
        />
      </el-form-item>
    </template>
    <!-- 积分 -->
    <template v-if="form.partType == 1 || form.partType == 3">
      <el-form-item>
        <el-form-item label-width="0px" prop="integralNum">
          <EasyNumberInput
            v-model="form.integralNum"
            :min="1"
            :max="9999"
            unit="个"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label-width="10px" prop="integralId">
          <el-select
            v-model="form.integralId"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="(item, key) in currencyList"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
    </template>
    <el-form-item label="免费次数：">
      每人&nbsp;&nbsp;
      <el-form-item label-width="10px" prop="freeNum">
        <EasyNumberInput
          v-model="form.freeNum"
          :min="0"
          :max="9999"
          unit="次"
          :precision="0"
        /> </el-form-item
      >&nbsp;&nbsp;
      <el-select
        v-model="form.freeType"
        placeholder="请选择"
        style="width: 100px"
      >
        <el-option
          v-for="(item, key) in freeType"
          :label="item"
          :value="Number(key)"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="参与总次数：">
      <el-radio-group v-model="form.partTotalLimit">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">限制</el-radio>
      </el-radio-group>
      <template v-if="form.partTotalLimit == 1">
        <el-form-item label-width="10px" prop="partTotalNum">
          <EasyNumberInput
            v-model="form.partTotalNum"
            :min="1"
            :max="9999"
            :precision="0"
            unit="次"
          />
        </el-form-item>
      </template>
    </el-form-item>
    <el-form-item label="参与次数：">
      <div class="flex-contain" v-for="(limit, index) in form.partLimit">
        每人&nbsp;&nbsp;
        <el-select
          v-model="limit.type"
          placeholder="请选择"
          style="width: 100px"
        >
          <el-option
            v-for="(item, key) in frequencyType"
            :label="item"
            :value="Number(key)"
          /> </el-select
        >&nbsp;&nbsp; 最多
        <el-form-item
          label-width="10px"
          :prop="`partLimit.${index}.limitNum`"
          :rules="[
            { required: true, message: '请填写限制次数', trigger: 'blur' },
          ]"
        >
          <EasyNumberInput
            v-model="limit.limitNum"
            :min="1"
            :max="9999"
            unit="次"
            :precision="0"
          ></EasyNumberInput>
        </el-form-item>
      </div>
    </el-form-item>
    <!-- 中奖限制 -->
    <template v-if="showPrizePool">
      <h3 class="collpase-title">中奖限制</h3>
      <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
        <el-radio-group v-model="form.lotteryTotalLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
        <template v-if="form.lotteryTotalLimit == 1">
          <el-form-item label-width="10px" prop="lotteryTotalNum">
            <EasyNumberInput
              v-model="form.lotteryTotalNum"
              :min="1"
              :max="9999"
              :precision="0"
              unit="次"
            />
          </el-form-item>
        </template>
      </el-form-item>
      <el-form-item label="中奖次数：">
        <el-radio-group v-model="form.lotteryLimitType">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.lotteryLimitType == 1">
        <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
          每人&nbsp;&nbsp;
          <el-select
            v-model="limit.type"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="(item, key) in frequencyType"
              :label="item"
              :value="Number(key)"
            /> </el-select
          >&nbsp;&nbsp; 最多
          <el-form-item
            label-width="10px"
            :prop="`lotteryLimit.${index}.limitNum`"
            :rules="[
              { required: true, message: '请填写限制次数', trigger: 'blur' },
            ]"
          >
            <EasyNumberInput
              v-model="limit.limitNum"
              :min="1"
              :max="9999"
              unit="次"
              :precision="0"
            ></EasyNumberInput>
          </el-form-item>
        </div>
      </el-form-item>
    </template>
  </el-form>
  <h3 class="collpase-title">题目配置</h3>
  <QuestionSelector v-model="answerConfig.questionList" @change="updateData" />
  <el-form
    ref="answerRef"
    :model="answerConfig"
    :rules="rules"
    label-width="auto"
    :disabled="activityReadonly"
  >
    <h3 class="collpase-title">答题配置</h3>
    <el-form-item label="题目数量：" prop="questionNum">
      <EasyNumberInput
        v-model="answerConfig.questionNum"
        :min="1"
        :max="10"
        unit="题"
        :precision="0"
        @change="updateData"
        style="width: 150px"
      />
    </el-form-item>
    <el-form-item label="出题顺序：" prop="orderType">
      <el-radio-group v-model="answerConfig.orderType">
        <el-radio :label="0">随机</el-radio>
        <el-radio :label="1">由易到难随机</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="答题时间：" prop="ansTimeLimit">
      <el-radio-group v-model="answerConfig.ansTimeLimit" @change="updateData">
        <el-radio :label="0">不限</el-radio>
        <el-radio :label="1">
          <el-form-item label-width="0"
            >总时间限制
            <el-form-item
              v-if="answerConfig.ansTimeLimit == 1"
              label-width="10px"
              prop="ansTotalTime"
            >
              <EasyNumberInput
                v-model="answerConfig.ansTotalTime"
                :min="1"
                :max="9999"
                :precision="0"
                unit="秒"
                style="width: 150px"
                @change="updateData"
              />
            </el-form-item>
          </el-form-item>
        </el-radio>
        <el-radio :label="2">
          <el-form-item label-width="0"
            >每题时间限制
            <el-form-item
              v-if="answerConfig.ansTimeLimit == 2"
              label-width="10px"
              prop="ansPerTime"
            >
              <EasyNumberInput
                v-model="answerConfig.ansPerTime"
                :min="1"
                :max="9999"
                :precision="0"
                unit="秒"
                style="width: 150px"
                @change="updateData"
              />
            </el-form-item>
          </el-form-item>
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="答题分数：" prop="scoreType">
      <el-radio-group
        v-model="answerConfig.scoreType"
        @change="changeScoreType"
      >
        <el-radio :label="0">统一分数</el-radio>
        <el-radio :label="1">题目类型分数</el-radio>
        <el-radio :label="2">题目难度分数</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item
      v-if="answerConfig.scoreType == 0"
      v-for="(scoreItem, sIndex) in answerConfig.typeScoreList"
      :prop="`typeScoreList.${sIndex}.perScore`"
      :rules="[{ required: true, message: '请填写分数', trigger: 'blur' }]"
    >
      每题&nbsp;&nbsp;<EasyNumberInput
        v-model="scoreItem.perScore"
        :min="1"
        :max="9999"
        unit="分"
        :precision="0"
        style="width: 150px"
      />
    </el-form-item>
    <el-form-item
      v-if="answerConfig.scoreType == 1"
      v-for="(scoreItem, sIndex) in answerConfig.typeScoreList"
    >
      单选题<el-form-item
        label-width="10px"
        :prop="`typeScoreList.${sIndex}.checkScore`"
        :rules="[{ required: true, message: '请填写分数', trigger: 'blur' }]"
      >
        <EasyNumberInput
          v-model="scoreItem.checkScore"
          :min="1"
          :max="9999"
          unit="分"
          :precision="0"
          style="width: 150px"
        />
      </el-form-item>
      &nbsp;&nbsp;多选题
      <el-form-item
        label-width="10px"
        :prop="`typeScoreList.${sIndex}.selectScore`"
        :rules="[{ required: true, message: '请填写分数', trigger: 'blur' }]"
      >
        <EasyNumberInput
          v-model="scoreItem.selectScore"
          :min="1"
          :max="9999"
          unit="分"
          :precision="0"
          style="width: 150px"
        />
      </el-form-item>
    </el-form-item>
    <el-form-item v-if="answerConfig.scoreType == 2">
      <el-form-item
        label-width="10px"
        v-for="(scoreItem, sIndex) in answerConfig.typeScoreList"
        style="margin-bottom: 15px"
      >
        {{ scoreItem.star }}星<el-form-item
          label-width="10px"
          :prop="`typeScoreList.${sIndex}.starScore`"
          :rules="[{ required: true, message: '请填写分数', trigger: 'blur' }]"
        >
          <EasyNumberInput
            v-model="scoreItem.starScore"
            :min="1"
            :max="9999"
            unit="分"
            :precision="0"
            @change="onChangeShareNum"
            style="width: 150px"
          />
        </el-form-item>
      </el-form-item>
    </el-form-item>
    <el-form-item label="通关条件：" prop="completeQua">
      <el-radio-group v-model="answerConfig.completeQua">
        <el-radio :label="0">全部答完</el-radio>
        <el-radio :label="1">答错即止</el-radio>
        <el-radio :label="2"
          ><el-form-item label-width="0"
            >获得<el-form-item
              label-width="10px"
              prop="completeScore"
              :rules="[{ validator: validateTimer, trigger: 'blur' }]"
            >
              <EasyNumberInput
                v-model="answerConfig.completeScore"
                :min="1"
                :max="9999"
                :precision="0"
                unit="分"
                style="width: 150px"
              /> </el-form-item></el-form-item
        ></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="答题奖励：" prop="rewardLimit">
      <el-radio-group v-model="answerConfig.rewardLimit">
        <el-radio :label="0">不限分数</el-radio>
        <el-radio :label="1">限制分数</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item
      v-if="answerConfig.rewardLimit == 0"
      v-for="(config, cIndex) in answerConfig.rewardConfigList"
    >
      通关即可获得<el-form-item label-width="10px">
        <el-form-item
          label-width="0"
          v-for="(reward, rIndex) in config.rewardList"
        >
          <RewardSelector
            v-model="config.rewardList[rIndex]"
            :subType="form.subType"
            lottery
            :prizeAreas="prizeAreas"
            :prefix="`rewardConfigList.${cIndex}.rewardList.${rIndex}.`"
            @change="updateData"
            @addPool="addPool"
            @addPrize="addPoolPrize"
          />
        </el-form-item>
      </el-form-item>
    </el-form-item>
    <template v-else-if="answerConfig.rewardLimit == 1">
      <el-form-item v-for="(config, cIndex) in answerConfig.rewardConfigList">
        达到<el-form-item
          label-width="10px"
          :prop="`rewardConfigList.${cIndex}.score`"
          :rules="[{ required: true, message: '请填写分数', trigger: 'blur' }]"
        >
          <EasyNumberInput
            v-model="config.score"
            :min="1"
            :max="9999"
            :precision="0"
            unit="分"
          /> </el-form-item
        >&nbsp;&nbsp;获得<el-form-item label-width="10px">
          <el-form-item
            label-width="0"
            v-for="(reward, rIndex) in config.rewardList"
          >
            <RewardSelector
              v-model="config.rewardList[rIndex]"
              :subType="form.subType"
              lottery
              :prizeAreas="prizeAreas"
              :prefix="`rewardConfigList.${cIndex}.rewardList.${rIndex}.`"
              @change="updateData"
              @addPool="addPool"
              @addPrize="addPoolPrize"
            />
          </el-form-item>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="plus" @click="addReward"
          >添加奖励</el-button
        >
      </el-form-item>
    </template>
  </el-form>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="showPrizePool ? [1, 2] : [2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    :quote="quotePrize"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
